package com.example.demo.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demo.controller.BaseController;
import com.example.demo.entity.SysFile;
import com.example.demo.service.SysFileService;
import com.example.demo.utils.enu.MinioBucketEnum;
import com.example.demo.utils.enu.UserInfoEnu;
import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.Bucket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class MinioUtil {
    @Autowired
    MinioClient minioClient;
    @Autowired
    SysFileService sysFileService;
    @Value("${minio.endpoint}")
    private String endpoint;

    /**
     * 重载
     * 文件上传Minio，需要指定要保存到的Bucket，使用MinioBucketEnum枚举类
     *
     * @param file
     * @param bucketEnum
     * @throws IOException
     * @throws ServerException
     * @throws InsufficientDataException
     * @throws ErrorResponseException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws InvalidResponseException
     * @throws XmlParserException
     * @throws InternalException
     */
    public void upload(MultipartFile file, MinioBucketEnum bucketEnum) throws Exception {
        if (bucketEnum != null) {
            try {
                if (bucketEnum != null) {
                    this.saveFile(file, bucketEnum.getBucket());
                } else {
                    throw new Exception("MinioBucketEnum Is NULL");
                }
            } catch (Exception e) {
                throw new Exception("上传失败！ 报错信息：" + e.getMessage());
            }
        }
    }

    /**
     * 重载
     * 文件上传Minio，须指定要保存到的Bucket，字符串类型
     *
     * @param file
     * @param bucketName
     * @throws IOException
     * @throws ServerException
     * @throws InsufficientDataException
     * @throws ErrorResponseException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws InvalidResponseException
     * @throws XmlParserException
     * @throws InternalException
     */
    public void upload(MultipartFile file, String bucketName) throws Exception {
        try {
            if (bucketName != null && !bucketName.equals("")) {
                boolean exist = bucketExist(bucketName);
                if (exist) {
                    this.saveFile(file, bucketName);
                } else {
                    throw new Exception("Bucket:" + bucketName + "不存在！");
                }
            } else {
                throw new Exception("BucketName is Null or Empty:");
            }
        } catch (Exception e) {
            throw new Exception("上传失败！ 报错信息：" + e.getMessage());
        }
    }

    private String geneFilePath(SysFile sysFile, String bucketName) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(endpoint);
        stringBuilder.append("/");
        stringBuilder.append(bucketName);
        stringBuilder.append("/");
        stringBuilder.append(sysFile.getFileUuidName());
        return stringBuilder.toString();
    }

    private void saveFile(MultipartFile file, String bucketName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        try {
            UUIDUtil uuidUtil = new UUIDUtil();
            String fileName = file.getOriginalFilename();
            String uuidName = new StringBuilder().append(uuidUtil.getUUID()).append("_").append(fileName).toString();
            String fileType = file.getContentType();
            String fileSize = String.valueOf(file.getSize());
            SysFile sysFile = new SysFile();
            sysFile.setFileName(fileName);
            sysFile.setFileUuidName(uuidName);
            sysFile.setFileSize(fileSize);
            sysFile.setFileType(fileType);
            sysFile.setFilePath(this.geneFilePath(sysFile, bucketName));
            sysFile.setBucketName(bucketName);
            sysFile.setFileUploader("");
            sysFile.setCreateTime(new Date());
            sysFile.setUpdateTime(new Date());
            PutObjectArgs args = PutObjectArgs.builder().object(uuidName).bucket(bucketName).stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();
            minioClient.putObject(args);
            sysFileService.save(sysFile);
        } catch (Exception e) {
            throw e;
        }
    }

    public List<String> getBucketNameList() throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        List<Bucket> buckets = minioClient.listBuckets();
        List<String> names = new ArrayList<>();
        for (Bucket bucket : buckets) {
            names.add(bucket.name());
        }
        return names;
    }

    public boolean delete(String uuid, String bucketName) throws Exception {
        if (bucketExist(bucketName)) {
            return deleteFile(uuid, bucketName);
        } else {
            return false;
        }
    }

    public boolean delete(String uuid, MinioBucketEnum bucketEnum) throws Exception {
        if (bucketExist(bucketEnum.getBucket())) {
            return deleteFile(uuid, bucketEnum.getBucket());
        } else {
            return false;
        }
    }

    private boolean deleteFile(String uuid, String bucketName) {
        try {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(uuid).build());
            boolean remove = sysFileService.remove(new LambdaQueryWrapper<SysFile>().eq(SysFile::getFileUuidName, uuid).eq(SysFile::getBucketName, bucketName));
            return remove;
        } catch (Exception e) {
            return false;
        }
    }

    public boolean bucketExist(String bucketName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        if (bucketName != null && !bucketName.equals("")) {
            boolean exist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            return exist;
        } else {
            return false;
        }
    }

    public boolean createBucket(String bucketName) throws Exception {
        minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        return true;
    }

}
